package com.impression.chq.ui;

import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.impression.chq.Utils.FileUtils;
import com.impression.chq.adapter.GridAdapter;
import com.impression.chq.home.R;
import com.impression.chq.http.HttpUtils;
import com.impression.chq.http.OkHttpEngine;
import com.impression.chq.http.ResultCallback;
import com.impression.chq.model.Meizi;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author CHQ
 * @version 1.0
 * @date 创建时间： 2016/11/30 10:46
 * @parameter
 * @return
 */
public class HomeFragment extends Fragment {
    private CoordinatorLayout coordinatorLayout;
    private View view;
    private ItemTouchHelper itemTouchHelper;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private GridLayoutManager gridLayoutManager;
    private GridAdapter mAdapter;
    private List<Meizi> meizis;
    private int page = 1;
    private int lastVisibleItem;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home,container,false);
        initUI();
        setListener();
        getData();
        return view;
    }

    private void initUI(){
        coordinatorLayout = (CoordinatorLayout) view.findViewById(R.id.home_coordinatorLayout);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        gridLayoutManager = new GridLayoutManager(getActivity(),3,GridLayoutManager.VERTICAL,false); //设置为一个3列的纵向网格布局
        recyclerView.setLayoutManager(gridLayoutManager);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
        //调整SwipeRefreshLayout的位置
        //swipeRefreshLayout.setProgressViewOffset(false,0,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));
    }

    /***
     * 加载数据
     */
    private void getData() {
        OkHttpEngine.getInstance().getAsynHttp("http://gank.io/api/data/福利/10/"+page, new ResultCallback() {
            @Override
            public void onStart() {
                //设置swipeRefreshLayout为刷新状态
                swipeRefreshLayout.setRefreshing(true);
            }

            @Override
            public void onError(Call call, Exception e) {
                //停止swipeRefreshLayout加载动画
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onSuccess(String result) throws IOException {
                JSONArray array = null;
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    array = jsonObject.getJSONArray("results");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if(meizis == null||meizis.size()==0){
                    meizis = new ArrayList<Meizi>();
                    for(int i=0; i<array.length();i++) {
                        Meizi meizi = new Meizi();
                        meizi.setPage(page);
                        try {
                            meizi.setUrl(array.getJSONObject(i).getString("url"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        meizis.add(meizi);
                    }
                }else {
                    for(int i=0; i<array.length();i++) {
                        Meizi meizi = new Meizi();
                        meizi.setPage(page);
                        try {
                            meizi.setUrl(array.getJSONObject(i).getString("url"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        meizis.add(meizi);
                    }
                }

                if(mAdapter==null){
                    mAdapter = new GridAdapter(getActivity(),meizis);
                    recyclerView.setAdapter(mAdapter);

                    //实现适配器自定义的点击监听
                    mAdapter.setOnItemClickListener(new GridAdapter.OnRecyclerViewItemClickListener() {
                        @Override
                        public void onItemClick(View view) {
                            int position = recyclerView.getChildAdapterPosition(view);
                            Toast.makeText(getActivity(),"position="+position,Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onItemLongClick(View view) {
                            itemTouchHelper.startDrag(recyclerView.getChildViewHolder(view));
                        }
                    });
                    itemTouchHelper.attachToRecyclerView(recyclerView);
                }else {
                    //让适配器刷新数据
                    mAdapter.notifyDataSetChanged();
                }
                //停止swipeRefreshLayout加载动画
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private void setListener(){
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getData();
            }
        });
        itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                int dragFlags=0;
                if(recyclerView.getLayoutManager() instanceof StaggeredGridLayoutManager ||recyclerView.getLayoutManager() instanceof GridLayoutManager){
                    dragFlags=ItemTouchHelper.UP|ItemTouchHelper.DOWN|ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;
                }
                return makeMovementFlags(dragFlags,0);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int from=viewHolder.getAdapterPosition();
                int to=target.getAdapterPosition();
                Meizi moveItem = meizis.get(from);
                meizis.remove(from);
                meizis.add(to,moveItem);
                mAdapter.notifyItemMoved(from,to);
                return true;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

            }

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }
        });

        //recyclerview滚动监听
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //0：当前屏幕停止滚动；1时：屏幕在滚动 且 用户仍在触碰或手指还在屏幕上；2时：随用户的操作，屏幕上产生的惯性滑动；
                // 滑动状态停止并且剩余少于两个item时，自动加载下一页
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem +2>= gridLayoutManager.getItemCount()) {
                    page += 1;
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
//                获取加载的最后一个可见视图在适配器的位置。
                lastVisibleItem = gridLayoutManager.findLastVisibleItemPosition();
            }
        });

    }
}
